package tools.crawler.test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.easywan.util.StringsUtils;
import com.easywan.util.Utils;

import tools.crawler.utils.HttpRequest;

public class CrawlerController {
	public void executePage(
			String url,//请求的页面
			List<Field> fields,//需要获取的东西
			FileVo file,//主要是用来判断是否保存到文件的
			//insert into article(name,title,context,createtime)values(?,?,?,?) 
			//String mysql//sql语句
			Boolean isMySql,
			String encode
			){
		HttpRequest.setCharset(encode);
		System.out.println("url:"+url);
		String html = HttpRequest.get(url).body();
		/*if(0<html.indexOf("charset=gb2312")){
			HttpRequest.setCharset("gb2312");
		}else{
			HttpRequest.setCharset("UTF-8");
		}*/
		Map<String,String> context = new HashMap<>();//匹配完的
		for(Field f:fields){
			String name = f.getName();
			switch(f.getConditionType()){
			case CONDITION_MID:
				String[] s2 = (String[]) f.getCondition();
				String value = StringsUtils.findMid(html,s2[0],s2[1]);
				context.put(name, value);
				context.put("createtime", Utils.getNowDate().toString());
				break;
			}
		}
		try{
		Class t = Class.forName("com.mysql.jdbc.Driver");
		Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1/easywan","root","");
		PreparedStatement pstmt = conn.prepareStatement("insert into article(createtime,title,context,uid) values(?,?,?,1)");
		pstmt.setString(1, context.get("createtime"));
		pstmt.setString(2, context.get("title"));
		pstmt.setString(3, context.get("context"));
		int i = pstmt.executeUpdate();
		System.out.println(i);
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
	
	
	public List<String> getUrl(String url,String encode,String string1,String string2){
		List<String> ss = null;//new ArrayList<>();
		HttpRequest.setCharset(encode);
		String html = HttpRequest.get(url).body();
		ss = StringsUtils.findMidAll(html, string1, string2);
		
		return ss;
	}
}
